﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Magnet : MonoBehaviour
{
    public GameObject obj=null;    //磁铁吸附的物体
    //获取参数
    #region
    public Transform Player_transform;

    public LayerMask PlayerLayer;
    public bool isUsing;

    public bool isLocking;

    #endregion

    //判断
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            collision.gameObject.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Kinematic;
            collision.gameObject.transform.SetParent(Player_transform);
            obj = collision.gameObject;
            collision.gameObject.GetComponent<Player>().parent = transform.parent.gameObject;
        }
    }
   
    
    private void OnTriggerStay2D(Collider2D collision)
    {
            if (collision.gameObject.CompareTag("Player"))
            {
                //collision.gameObject.GetComponent<Rigidbody2D>().gravityScale = 0;
                //if (Mathf.Abs(collision.gameObject.transform.position.x - this.transform.position.x) < 1f || Mathf.Abs(collision.gameObject.transform.position.y - this.transform.position.y) < 1f)
                //if ((collision.gameObject.transform.position - this.transform.position).sqrMagnitude < 0.01f)
                if ((collision.gameObject.transform.position - this.transform.position).sqrMagnitude < 0.5f)
                {
                    return;
                }
                else
                {
                    //collision.gameObject.transform.position = Vector2.Lerp(collision.gameObject.transform.position, this.transform.position, 10 * Time.deltaTime);
                    collision.gameObject.transform.position = Vector2.Lerp(collision.gameObject.transform.position, this.transform.position, 0.2f);
                }
            }
    }
    private void OnTriggerExit2D(Collider2D collision)
    {   
            if (collision.gameObject.CompareTag("Player"))
            {
                collision.gameObject.GetComponent<Rigidbody2D>().bodyType = RigidbodyType2D.Dynamic;
                RemoveChildren();
            }
    }
    public void RemoveChildren()
    {
        if (obj)
        {
            obj.GetComponent<Player>().parent = null;
            obj.gameObject.transform.parent = null;
            obj = null;
            Debug.Log(obj);
        }
    }
}